package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.bean.SysUser;
import com.zzw.springboot.mapper.SysUserMapper;
import com.zzw.springboot.service.SysUserService;
import com.zzw.springboot.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    // 用户缓存前缀
    private static final String USER_CACHE_PREFIX = "user:";
    // 用户缓存时间（秒）
    private static final long USER_CACHE_TIMEOUT = 3600;

    /**
     * 保存用户时对密码进行加密
     */
    @Override
    public boolean save(SysUser user) {
        // 加密密码
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return super.save(user);
    }
    
    /**
     * 根据用户ID获取用户信息，优先从Redis缓存中获取
     * @param id 用户ID
     * @return 用户对象
     */
    @Override
    public SysUser getById(Serializable id) {
        // 构造缓存键
        String cacheKey = USER_CACHE_PREFIX + id;
        
        // 尝试从缓存中获取
        Object cacheUser = redisUtil.get(cacheKey);
        if (cacheUser != null) {
            return (SysUser) cacheUser;
        }
        
        // 缓存中不存在，从数据库查询
        SysUser user = super.getById(id);
        if (user != null) {
            // 将结果存入缓存
            redisUtil.set(cacheKey, user, USER_CACHE_TIMEOUT);
        }
        
        return user;
    }
    
    /**
     * 更新用户信息，同时更新缓存
     * @param user 用户对象
     * @return 是否成功
     */
    @Override
    public boolean updateById(SysUser user) {
        // 如果要更新密码，则需要加密
        if (StringUtils.hasText(user.getPassword())) {
            SysUser originalUser = getById(user.getId());
            // 如果密码未变更，则不需要重新加密
            if (!user.getPassword().equals(originalUser.getPassword())) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }
        }
        
        // 更新数据库
        boolean result = super.updateById(user);
        
        if (result) {
            // 更新成功，删除缓存
            String cacheKey = USER_CACHE_PREFIX + user.getId();
            redisUtil.del(cacheKey);
        }
        
        return result;
    }
    
    /**
     * 删除用户，同时删除缓存
     * @param id 用户ID
     * @return 是否成功
     */
    @Override
    public boolean removeById(Serializable id) {
        // 删除数据库记录
        boolean result = super.removeById(id);
        
        if (result) {
            // 删除成功，删除缓存
            String cacheKey = USER_CACHE_PREFIX + id;
            redisUtil.del(cacheKey);
        }
        
        return result;
    }

    @Override
    public Boolean changePassword(Integer id, String newPassword) {
        SysUser sysUser = sysUserMapper.isExistUserById(id);
        if (sysUser == null) {
            return false;//说明不存在当前id的用户
        }
        // 加密密码
        sysUser.setPassword(passwordEncoder.encode(newPassword));

        if(sysUserMapper.updateById(sysUser) < 1){
            return false;//修改失败
        }
        
        // 密码修改成功，删除缓存
        String cacheKey = USER_CACHE_PREFIX + id;
        redisUtil.del(cacheKey);
        
        return true;//修改成功
    }

    //状态修改
    @Override
    public boolean changeStatus(SysUser sysUser) {
        SysUser originalUser = sysUserMapper.isExistUserById(sysUser.getId());
        if (originalUser == null) {
            return false;//说明不存在当前id的用户
        }
        originalUser.setStatus(sysUser.getStatus());

        if(sysUserMapper.updateById(originalUser) < 1){
            return false;//修改失败
        }
        
        // 状态修改成功，删除缓存
        String cacheKey = USER_CACHE_PREFIX + sysUser.getId();
        redisUtil.del(cacheKey);
        
        return true;//修改成功
    }

    @Override
    public boolean resetPwd(SysUser sysUser) {
        SysUser originalUser = sysUserMapper.isExistUserById(sysUser.getId());
        if (originalUser == null) {
            return false;//说明不存在当前id的用户
        }
        // 加密密码
        originalUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));

        if(sysUserMapper.updateById(originalUser) < 1){
            return false;//修改失败
        }
        
        // 密码重置成功，删除缓存
        String cacheKey = USER_CACHE_PREFIX + sysUser.getId();
        redisUtil.del(cacheKey);
        
        return true;//修改成功
    }
}
